package com.jewaton.auth.commons.operationlog.dao;

import com.jewaton.auth.commons.dao.BaseDAO;
import com.jewaton.auth.commons.operationlog.entity.Operatelog;
import com.jewaton.auth.commons.operationlog.entity.OperatelogCriteria;
import com.jewaton.auth.commons.util.PageQueryHibernateCallback;
import com.jewaton.auth.commons.util.PagedQueryResult;
import com.jewaton.auth.commons.util.Pager;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**   
*    
* 日志数据底层操作类
*
*/ 
@Repository(value="operatelogDAO")
public class OperatelogDAO extends BaseDAO{

    private static final Log logger = LogFactory.getLog(OperatelogDAO.class);

    private StringBuffer buf ;
	
	public Operatelog findOperatelogById(Integer id){
		return getHibernateTemplate().get(Operatelog.class, id);
	}
	
	@SuppressWarnings("unchecked")
	public Pager findOperatelogAll(Integer start,Integer end){
		buf = new StringBuffer();
		buf.append("FROM Operatelog log ORDER BY log.createTime DESC");
		return findPageList(buf.toString(), start, end);
	}
	
	
	public PagedQueryResult findOperatelogPage(Integer pageNo, Integer pageSize, OperatelogCriteria criteria){
		List<Criterion> criterionList = new ArrayList<Criterion>();
		List<Order> orderList = new ArrayList<Order>();
		
//		if(!"".equals(criteria.getMsgTo()) && criteria.getMsgTo() != null){
//			criterionList.add(Restrictions.like("msgTo", "%"+ criteria.getMsgTo() +"%"));
//		}
//		if(!"".equals(criteria.getSubject()) && criteria.getSubject() != null){
//			criterionList.add(Restrictions.like("subject","%"+ criteria.getSubject() +"%"));
//		}
		switch(criteria.getSortBy()){
//			case PostMsgCriteria.SORT_BY_ADD_DATE:
			case 1:
				orderList.add(criteria.isSortAscending()
						? Order.asc("createTime")
						: Order.desc("createTime"));
				break;
		}
		return (PagedQueryResult) getHibernateTemplate().execute(
				new PageQueryHibernateCallback(pageNo, pageSize,
						criterionList, orderList, Operatelog.class));
	}

	public Pager findOperatelogPage(Map<String,Object> param, Integer pageNo, Integer pageSize) {
		try {
			StringBuffer buf1 = new StringBuffer();
			buf1.append("FROM Operatelog log where 1=1 ");
			String keywords = (String)param.get("keywords");
			String startTime = (String)param.get("startTime");
			String endTime = (String)param.get("endTime");

			Map<String,Object> params = new HashMap<String,Object>();
			if(StringUtils.isNotBlank(keywords)){
				buf1.append(" and (log.moduleName like :keywords " +
						"or log.typeName like :keywords " +
						"or log.message like :keywords " +
                        "or log.account.username like :keywords ");
				buf1.append(" ) ");
				params.put("keywords", "%" + keywords + "%");
			}
			if(StringUtils.isNotBlank(startTime)){
				buf1.append(" and log.createTime >= to_date(:startTime,'yyyy-mm-dd hh24:mi:ss')");
				params.put("startTime", startTime);
			}
			if(StringUtils.isNotBlank(endTime)){
				buf1.append(" and log.createTime <= to_date(:endTime,'yyyy-mm-dd hh24:mi:ss')");
				params.put("endTime", endTime);
			}
			buf1.append(" ORDER BY log.createTime DESC");
            logger.debug(buf1.toString());
			return findPageList(buf1.toString(),params, pageNo, pageSize);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

    /**
     * 删除日志，根据选中的记录或选择的日志删除
     * @param param
     * @return
     */
    public int delLogs(Map<String,Object> param){
        int count = 0;
        String fns = (String)param.get("fns");
        String startTime = (String)param.get("startTime");
        String endTime = (String)param.get("endTime");
        if(StringUtils.isBlank(fns)&&StringUtils.isBlank(startTime)&&StringUtils.isBlank(endTime))
            return count;
        StringBuilder sql = new StringBuilder("delete Operatelog log where 1=1 ");
        if(StringUtils.isNotBlank(fns)){
            sql.append(" and log.lid in (:fns) ");
            Long[] ids = new Long[fns.length()];
            String[] fn = fns.split(",");
            for (int i =0 ; i < fn.length;i++)
                ids[i] = Long.valueOf(fn[i]);
            param.put("fns",ids);
        }
        if(StringUtils.isNotBlank(startTime)){
            sql.append(" and log.createTime >= to_date(:startTime,'yyyy-mm-dd hh24:mi:ss')");
            param.put("startTime", startTime);
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and log.createTime <= to_date(:endTime,'yyyy-mm-dd hh24:mi:ss')");
            param.put("endTime", endTime);
        }
        Query query =  getSession().createQuery(sql.toString());
        setQueryParameters(param,query);
        count = query.executeUpdate();
        return count;
    }

    /**
     * 查询日志，根据选中的记录或选择的日志，为删除准备。
     * 备份开启的情况下
     * @param param
     * @return
     */
    public List<Operatelog> findelLogs(Map<String,Object> param){
        String fns = (String)param.get("fns");
        String startTime = (String)param.get("startTime");
        String endTime = (String)param.get("endTime");
        if(StringUtils.isBlank(fns)&&StringUtils.isBlank(startTime)&&StringUtils.isBlank(endTime))
            return new ArrayList<Operatelog>(0);
        StringBuilder sql = new StringBuilder("from Operatelog log where 1=1 ");
        if(StringUtils.isNotBlank(fns)){
            sql.append(" and log.lid in (:fns) ");
            Long[] ids = new Long[fns.length()];
            String[] fn = fns.split(",");
            for (int i =0 ; i < fn.length;i++)
                ids[i] = Long.valueOf(fn[i]);
            param.put("fns",ids);
        }
        if(StringUtils.isNotBlank(startTime)){
            sql.append(" and log.createTime >= to_date(:startTime,'yyyy-mm-dd hh24:mi:ss')");
            param.put("startTime", startTime);
        }
        if(StringUtils.isNotBlank(endTime)){
            sql.append(" and log.createTime <= to_date(:endTime,'yyyy-mm-dd hh24:mi:ss')");
            param.put("endTime", endTime);
        }
        sql.append(" order by log.createTime desc");
        Query query =  getSession().createQuery(sql.toString());
        setQueryParameters(param,query);
        return query.list();
    }

    /**
     * 删除集合
     * @param logs
     */
    public void delLogList(List<Operatelog> logs){
        getHibernateTemplate().deleteAll(logs);
    }
	
}
